package hotel.meituan.oversea.biz.task;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CallbackConstants;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.JacksonUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.vo.meituan.request.order.MtHotelOrderCheckParamVo;
import hotel.base.oversea.vo.meituan.response.order.MtHotelOrderCheckVo;
import hotel.meituan.oversea.api.entity.MtHotelGoodsPrice;
import hotel.meituan.oversea.biz.config.service.RedisService;
import hotel.meituan.oversea.biz.service.MtHotelGoodsPriceService;
import hotel.meituan.oversea.biz.service.MtHotelOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;


@Slf4j
@Component
public class MeituanJobBookingUpdateAllSaleGoodsByOneHotelTask {
    private String timestamp = "Mjbugsit"+String.valueOf(System.currentTimeMillis());
    @Autowired
    private MeituanJobBookingUpdateGoodsSwInventoryTask meituanJobBookingUpdateGoodsSwInventoryTask;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MtHotelOrderService mtHotelOrderService;
    @Autowired
    private MtHotelGoodsPriceService mtHotelGoodsPriceService;
    private void setTimestamp(String timestamp){
        this.timestamp = timestamp;
    }

    //@Async 标识这个方法异步执行，可返回void或Future

    /**
     * {"code":6,"desc":"库存不足","priceModels":[],"remainRoomNum":0}
     * {"code":3,"desc":"产品goodsId:17387288不可预订, goodsStatus:0","priceModels":[]}
     *
     *{"code":0,"priceModels":[{"date":"2020-10-02","dayType":0,"salePrice":75600,"subPrice":3780,"subRatio":500}],"remainRoomNum":999}
     *
     */
    @Async
    public void executeUpdateAllInventory(MtHotelOrderCheckVo mtHotelOrderCheckVo,String mtHotelId,String type,MtHotelOrderCheckParamVo mtHotelOrderCheckParamVo1,String oneSwHotelId,String oneSwRoomId){
        log.info("MeituanJobBookingUpdateAllSaleGoodsByOneHotelTask executeUpdateAllInventory {} >>>>>>>>> 异步线程 进入轮询酒店产品  开始执行时间：{}",timestamp,DateUtil.getNowTime());
        String checkinDate = mtHotelOrderCheckParamVo1.getCheckinDate();
        String checkoutDate = mtHotelOrderCheckParamVo1.getCheckoutDate();
        Long daysOrder = DateUtil.dateDiff(checkinDate,"day",checkoutDate,"yyyy-MM-dd");
        if("stayDays".equals(type)){
            //连住多天的订单，单独对这几天该产品进行 查询库存
            Integer goodsId = mtHotelOrderCheckParamVo1.getGoodsId();
            String mtDate = checkinDate;
            for (int i = 0; i < daysOrder; i++) {
                String nextDay = DateUtil.formatDate(DateUtil.addDay(mtDate,1),"yyyy-MM-dd");
                if(ObjectUtils.isEmpty(goodsId)){
                    log.info("SwitchSaleRoomAboutIdsDto.goodsId 为空");
                    continue;
                }
                String redisPricekey = CallbackConstants.REDIS_KEY_CALLBACK_CHANGE_PRICE_HEAD +mtHotelId+"_"+mtHotelOrderCheckParamVo1.getGoodsId()+"_"+mtDate;
                Integer price = (Integer) redisService.get(redisPricekey);
                if(null == price){
                    MtHotelGoodsPrice oldPrice = mtHotelGoodsPriceService.queryGoodsByDate(mtHotelId,goodsId,mtDate);
                    price = oldPrice.getMtSalePrice();
                    log.info("executeUpdateAllInventory oldPrice={}", JSON.toJSONString(oldPrice));
                }
                if(null != price){
                    MtHotelOrderCheckParamVo mtHotelOrderCheckParamVo = new MtHotelOrderCheckParamVo();
                    mtHotelOrderCheckParamVo.setHotelId(Long.valueOf(mtHotelId));
                    mtHotelOrderCheckParamVo.setGoodsId(goodsId);
                    mtHotelOrderCheckParamVo.setCheckinDate(mtDate);
                    mtHotelOrderCheckParamVo.setCheckoutDate(nextDay);
                    mtHotelOrderCheckParamVo.setRoomNum(1);
                    mtHotelOrderCheckParamVo.setTotalPrice(price);
                    Result resultCheck = mtHotelOrderService.orderCheckApi(mtHotelOrderCheckParamVo);
                    log.info("executeUpdateAllInventory orderCheckApi：mtHotelOrderCheckParamVo={},resultCheck={}", JSON.toJSONString(mtHotelOrderCheckParamVo), JSON.toJSONString(resultCheck));
                    MtHotelOrderCheckVo mtHotelOrderCheckVo2 = JacksonUtil.objToBean(resultCheck.getData(), MtHotelOrderCheckVo.class);
                    if(resultCheck.getCode() == CommonConstants.SUCCESS && null != mtHotelOrderCheckVo2) {
                        //vesrion qyy 更新库存价格
                        meituanJobBookingUpdateGoodsSwInventoryTask.executeUpdateInventory("当前为酒店轮询上架产品跑下单前校验",oneSwHotelId,oneSwRoomId,mtDate,nextDay,mtHotelOrderCheckVo2.getRemainRoomNum(),mtHotelOrderCheckVo2,mtHotelId,Integer.valueOf(goodsId));
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
                mtDate = nextDay;
            }

        }else{
            //轮询
            //房态发生变化，，当前该酒店其他所有上架了的产品全部查询一遍 ，调用下单前校验进行查询（该接口最准确，不是缓存接口）
            //当前查询为create_room 不是实际上线的售卖房型，后期将爬虫获取实际上线房型（我们接口只是上架酒店实际上架了多少房型由携程那边做判断根据价格给我们上架）
            //当前处理过的酒店，主动查询那边将在20分钟内不再做主动查询处理
            /*Map map = new HashMap();
            map.put("mtHotelId",mtHotelId);
            Result<Object> result = RestTemplateUtils.post(CommonUrlConstants.SWITCHS_ONLINE_HOST+"/switchCreateRoom/getMtIdsAboutSwitchSaleRoomByMtHotelId",JSON.toJSONString(map),restTemplate);
            log.info("executeUpdateAllInventory getMtIdsAboutSwitchSaleRoomByMtHotelId={}",JSON.toJSONString(result));
            if(result.getCode()== CommonConstants.SUCCESS){
                List<SwitchSaleRoomAboutIdsDto> list = GsonUtils.jsonToList(GsonUtils.GsonString(result.getData()),SwitchSaleRoomAboutIdsDto.class);
                if(null != list && list.size()>0){
                    for (SwitchSaleRoomAboutIdsDto dto:list){
                        String swRoomId = dto.getSaleRoomId();
                        String swHotelId = dto.getHotelId();
                        Integer goodsId = dto.getMtGoodId();
                        String mtDate = DateUtil.getCurrTime().split(" ")[0];
                        String nextDay = DateUtil.formatDate(DateUtil.addDay(new Date(),1),"yyyy-MM-dd");
                        if(ObjectUtils.isEmpty(goodsId)){
                            log.info("SwitchSaleRoomAboutIdsDto.goodsId 为空");
                            continue;
                        }
                        String redisPricekey = CallbackConstants.REDIS_KEY_CALLBACK_CHANGE_PRICE_HEAD+mtHotelId+"_"+mtHotelOrderCheckParamVo1.getGoodsId()+"_"+mtDate;
                        Integer price = (Integer) redisService.get(redisPricekey);
                        if(null == price){
                            MtHotelGoodsPrice oldPrice = mtHotelGoodsPriceService.queryGoodsByDate(mtHotelId,goodsId,mtDate);
                            price = oldPrice.getMtSalePrice();
                            log.info("executeUpdateAllInventory oldPrice={}",JSON.toJSONString(oldPrice));
                        }
                        if(null != price){
                            MtHotelOrderCheckParamVo mtHotelOrderCheckParamVo = new MtHotelOrderCheckParamVo();
                            mtHotelOrderCheckParamVo.setHotelId(Long.valueOf(mtHotelId));
                            mtHotelOrderCheckParamVo.setGoodsId(goodsId);
                            mtHotelOrderCheckParamVo.setCheckinDate(mtDate);
                            mtHotelOrderCheckParamVo.setCheckoutDate(nextDay);
                            mtHotelOrderCheckParamVo.setRoomNum(1);
                            mtHotelOrderCheckParamVo.setTotalPrice(price);
                            Result resultCheck = mtHotelOrderService.orderCheckApi(mtHotelOrderCheckParamVo);
                            log.info("executeUpdateAllInventory orderCheckApi：mtHotelOrderCheckParamVo={},resultCheck={}",JSON.toJSONString(mtHotelOrderCheckParamVo),JSON.toJSONString(resultCheck));
                            MtHotelOrderCheckVo mtHotelOrderCheckVo2 = JacksonUtil.objToBean(resultCheck.getData(), MtHotelOrderCheckVo.class);
                            if(resultCheck.getCode() == CommonConstants.SUCCESS && null != mtHotelOrderCheckVo2) {
                                //vesrion qyy 更新库存价格
                                meituanJobBookingUpdateGoodsSwInventoryTask.executeUpdateInventory("当前为酒店轮询上架产品跑下单前校验",swHotelId,swRoomId,mtDate,nextDay,mtHotelOrderCheckVo2.getRemainRoomNum(),mtHotelOrderCheckVo2,mtHotelId,Integer.valueOf(goodsId));
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                            }
                        }
                    }
                }
            }*//////////////////////////////////////2021-02-05 防止限流接口，不做轮询

        }

        log.info("MeituanJobBookingUpdateAllSaleGoodsByOneHotelTask {} >>>>>>>>> 异步线程 进入轮询酒店产品  执行结束时间：{}",timestamp,DateUtil.getNowTime());

    }


}
